import './index.scss'
import waitApi from './api/index'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import Logo from '@/component/common/logo/Logo'
import { MyForm, MyFormProps } from '@/component/common/myForm'
import { Button, Flex, Form, Input } from 'antd'
import { useMessageApi } from '@/component/context/messageContext/message'
export default function Wait() {
  const location = useLocation()
  const [examState, setExamState] = useState<any>({})
  const [email, setEmail] = useState('')
  const messageApi = useMessageApi()
  const navigate = useNavigate()
  const getUserInfo = (str: string) => {
    if(!str){
      str = localStorage.getItem('key') as string
    }
    if(!str){
      return
    }
    waitApi.getUserInfo(str).then((data) => {
      
      setExamState(data)
    })
  }
  useEffect(() => {
    if (sessionStorage.getItem('token')) {
      navigate('/wait', { replace: true })
    }
    getUserInfo(location.search)
  }, [location.search, navigate])

  const [loginForm] = Form.useForm()

  const getToken = () => {
    loginForm
      .validateFields()
      .then((values) => {
        waitApi
          .getToken({
            email: email,
            userId: examState?.userInfo?.id,
            key: location.search,
          })
          .then((data: any) => {
            
            sessionStorage.setItem('token', data.token)
            messageApi.success('验证成功')
            navigate('/wait', { replace: true })
          })
      })
      .catch(() => {
        messageApi.error('请输入邮箱')
      })
  }

  const myformConf: MyFormProps = {
    name: 'loginForm',
    form: loginForm,
    conf: [
      {
        name: 'email',
        label: '邮箱',
        content: <Input placeholder="请输入邮箱" allowClear />,
        rules: [{ required: true }],
      },
    ],
    onValuesChange: (changedValues, allValues) => {
      setEmail(allValues.email)
    },
  }

  return (
    <div className="wait">
      <div className="logo">
        <Logo width={50} margin={'20px 0'}></Logo>
      </div>
      <div className="form">
        <h3>您好，{examState?.userInfo?.name}同学：</h3>
        <div className="form-box">
          <MyForm {...myformConf}></MyForm>
        </div>
        <Flex justify="center">
          <Button onClick={getToken}>验证</Button>
        </Flex>
      </div>
    </div>
  )
}
